//app.js
var com = require("./utils/common.js");
var util = require("./utils/util.js");
var more = 0;
var socketState;
App({
    onLaunch: function () {
        var that = this;
        wx.getSystemInfo({
            success: function (res) {
                that.systemInfo = res;
            }
        })
        that.checkVersion();
        that.wxLogin();
    },

    //微信登陆
    wxLogin() {
        var that = this;
        wx.login({
            success: res => {
                // 发送 res.code 到后台换取 openId
                that.getOpenid(res.code);
            }
        })
        wx.onNetworkStatusChange(function (res) {
            if (res.networkType == 'none') {
                that.showToast('网络连接断开');
            }
        })
    },
    //检查版本
    checkVersion() {
        var that = this;
        const version = wx.getSystemInfoSync().SDKVersion
        console.log(version, "version")
        if (that.compareVersion(version, '1.6.8') < 0) {
            // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用部分功能，请升级到最新微信版本后重试。'
            })
            return false;
        }
        return true;
    },
    compareVersion(v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }
        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    },

    //字体下载
    loadFontfun() {
        var that = this;
        console.log('调用了');
        wx.loadFontFace({
            family: 'huawen',
            source: 'url("' + that.globalData._network_path + 'censcbk.ttf")',
            success: function (res) {
                console.log('>>>>', res);
            },
            fail: function (res) {
                more += 1;
                if (more >= 5) {
                    return false;
                }
                that.loadFontfun();//再次调用字体
            }
        })
    },

    //发起网络请求,获取openid,session_key
    getOpenid: function (code) {
        var that = this;
        that.ajax({
            url: 'Common/Wx/getUserOpenid',
            data: {code: code},
            success: function (res) {
                if (res.data.code == 1000) {
                    wx.setStorageSync('openid', res.data.data.openid);
                } else if (res.data.code == -1000) {
                    that.wxLogin();//重新调取微信登录
                } else {
                    that.showToast(res.data.message);
                }
            }
        })
    },
    //跳转到登陆页面
    redirectLogin($msg = '') {
        console.log('1111111111');
        if (!util.isExitsVariable($msg)) {
            $msg = '您还未登录，请先登录';
        }
        var that = this;
        //避免重复登录
        var is_login = wx.getStorageSync('is_login');
        console.log('2222222', is_login);
        if (is_login) {
            return false;
        }
        console.log('2222222', is_login);

        wx.setStorageSync('is_login', true);
        that.showModal("", $msg, function () {
            wx.navigateTo({
                url: '/pages/myCenter/login/login',
            })
        }, function () {
            wx.setStorageSync('is_login', false);
        });
    },
    //获取登陆状态
    loginStatus(success, fail) {
        var that = this;
        //返回Promise对象
        return new Promise(
            function (resolve) {
                var token = wx.getStorageSync('token');
                var openid = wx.getStorageSync('openid');
                var loginType = wx.getStorageSync('loginType') == 2 ? 2 : 1;//登录类型，1工程人员、2行政人员(默认工程人员)
                var url = loginType == 2 ? 'api/Common/loginStatus' : 'Engineer/Engineers/loginStatus';
                var _url = loginType == 2 ? that.globalData.crm_url : that.globalData._url;
                console.log('返回的额数据', loginType, url, _url);
                wx.request({
                    method: "POST",
                    url: _url + url,
                    header: {
                        'token': token,// 默认值
                        'openid': openid
                    },
                    success: (resolve) => {
                        if (resolve.data.code == 1000) {
                            success(resolve);
                        } else if (resolve.data.code == -1006) {
                            that.showModal("", resolve.data.message, function () {
                                wx.navigateTo({
                                    url: '/pages/myCenter/login/login',
                                })
                            });
                        } else {
                            fail(resolve);
                        }

                    }, error: (resolve) => {
                        fail(resolve);
                    }
                })
            })
    },

    // 扫码
    scanning: function (success) {
        var that = this;
        wx.scanCode({
            success: (res) => {
                console.log(res)
                var values = '';
                if (res.result.indexOf('device_no=') > -1) { //缴费器码
                    var strs = res.result.split('?device_no=');
                    values = strs[1];
                } else { //缴费器码
                    var code = res.result.split(';')
                    if (!util.isExitsVariable(code) || code.length == 0) {
                        that.showToast('扫码失败');
                        return false;
                    }
                    if (code[2] && code[2].indexOf(":") != -1) {
                        var val = code[2].split(':');
                        if (!util.isExitsVariable(val) || val.length == 0) {
                            that.showToast('扫码失败');
                            return false;
                        }
                        values = val[1];
                    } else {
                        values = code[0];
                    }
                }
                success(values);

            },
            fail: (res) => {
                that.showToast('扫码失败，请重试！');
            }
        })
    },

    //保存formId
    saveFormId: function (formId) {
        console.log('****formId*****');
        var that = this;
        console.log(formId);
        var openid = wx.getStorageSync('openid');
        that.ajax({
            url: 'Common/Wx/saveFormId',
            data: {openid: openid, formId: formId},
            success: function (res) {
                console.log(res);
                if (res.data.code == 1000) {
                    console.log('保存formId成功');
                } else {
                    console.log('保存formId失败')
                }

            }
        })
    },
    // 修改工程人员位置
    updateLatlng: function (lat, lng) {
        var that = this;
        that.ajax({
            url: 'Engineer/Engineers/engineersEditInfo',
            method: 'POST',
            data: {
                lat: lat,
                lng: lng
            },
            success: function (res) {
                if (res.data.code == 1000) {
                    console.log('修改成功')
                }
            }
        })
    },
    //websocket
    webSocket() {
        var account = wx.getStorageSync("account");
        var that = this;
        if (!util.isExitsVariable(account)) {
            return false;
        }
        //创建一个 WebSocket 连接
        wx.connectSocket({
            url: that.globalData._socket_url,
            success: function (res) {
                console.log(res)
            }
        })
        //
        wx.onSocketOpen(function (res) {
            var arr = {};
            var that = this;
            var account = wx.getStorageSync("account");
            arr.controller_name = "Websocket";
            arr.method_name = "login_state";
            arr.data = account;
            var data = JSON.stringify(arr);
            wx.sendSocketMessage({
                data: data,
                success: function (res) {
                    console.log("发送", res);
                }
            })
            socketState = setInterval(function () {
                var data = {};
                data.controller_name = "Websocket",
                    data.method_name = "ping";
                data.data = account;
                data = JSON.stringify(data);
                wx.sendSocketMessage({
                    data: data,
                })
            }, 20000);
        })
        wx.onSocketMessage(function (res) {
            var data = JSON.parse(res.data);
            console.log("接收消息", data)
        })
        wx.onSocketClose(function (res) {
            console.log("关闭连接", res)
            // var login_time = wx.getStorageSync("login_time");
            // var time = new Date().getTime() - login_time;
            // clearInterval(socketState);
            // // if (time > 3600000) {
            //   console.log("请退出登陆")
            //   wx.removeStorageSync("account");
            //   wx.setStorageSync('isLogout', 1);
            //   wx.removeStorageSync('token');
            // wx.showModal({
            //   title: '',
            //   content: "该账号在其他缴费器登陆,若不是本人操作，建议及时修改密码",
            //   showCancel: false,
            //   success: function (res) {
            //     wx.navigateTo({
            //       url: '/pages/myCenter/login/login',
            //     })
            //   }
            // })
            //}
        })

    },
    //socket心跳
    socketPing() {
        console.log("sdssssss")
        socketState = setInterval(function () {
            var data = {};
            data.controller_name = "Websocket",
                data.method_name = "ping";
            data.data = account;
            data = JSON.stringify(data);
            wx.sendSocketMessage({
                data: data,
            })
        }, 20000);
    },
    //ajax 请求
    ajax(model) {
        var that = this;
        if (util.isExitsVariable(model.load)) {
            var msg = "加载中";
            if (util.isExitsVariable(model.msg)) {
                msg = model.msg;
            }
            wx.showLoading({
                title: msg,
            })
        }
        if (!util.isExitsVariable(model.method)) {
            model.method = "POST";
        }

        // 判断请求哪个接口
        if (model.url_type == 2) {
            //拼接url model.url_type == 2  仅代表crm后台请求
            if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
                model.url = this.globalData.crm_url + model.url;
            }
        } else {
            //拼接url
            if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
                model.url = this.globalData._url + model.url;
            }
        }

        //get参数拼接
        if (model.method == "get" && model.data !== undefined) {
            for (let k in model.data) {
                if (model.data[k].toString() !== '') {
                    model.url = model.url + "&" + k + "=" + model.data[k];
                }
            }
            model.data = '';
        }

        //返回Promise对象
        return new Promise(
            function (resolve) {
                var token = wx.getStorageSync('token');
                var openid = wx.getStorageSync('openid');
                wx.request({
                    method: model.method,
                    url: model.url,
                    header: {
                        'token': token, // 默认值
                        'client': that.globalData.client,//终端
                        'company': that.globalData.company_id,//公司ID
                        'role': that.globalData.role,//角色
                        'openid': openid,

                    },
                    data: model.data,
                    success: (resolve) => {
                        if (resolve.statusCode == 404) {
                            that.showToast('网络错误,请返回重试');
                        }
                        if (util.isExitsVariable(model.load)) {
                            wx.hideLoading();
                        }
                        if (resolve.data.code == -1005 || resolve.data.code == -1004) {
                            console.log('*************************');
                            that.redirectLogin();
                            return false;
                        }
                        if (resolve.data.code == -1006) {
                            that.redirectLogin(resolve.data.message);
                            return false;
                        }

                        model.success(resolve);

                    },
                    fail: () => {
                        that.showToast('网络请求失败');
                    }
                })
            }
        )
    },
    globalData: {
        company_id: 1,
        userInfo: null,
        _network_path: 'https://qn.hznysc.com/oven_engineer_weapp_image/company_default/',
        /**开发环境-s */
      //  _url: 'https://admin.cqthesis.cn/',
      //  crm_url:'http://hzadmin.cqthesis.cn/',
        //wx109200d9d5977713
        /**开发环境-e */

        /**体验环境-s */
        _url: 'https://api.hznysc.com/',
        crm_url:'https://boss.hznysc.com/',
        // /**体验环境-e */
        client: 1,//终端1微信 2支付宝
        role: 5,//角色 端1总后台 2运营 3行政 4用户 5工程
    },
    //弹窗MODEL
    showModal(title = "提示", content = "", success = function () {
    }, cancel = function () {
    }) {
        wx.showModal({
            title: title,
            content: content,
            showCancel: false,
            success: function (res) {
                if (res.confirm) {
                    success();
                } else if (res.cancel) {
                    cancel();
                } else if (!res.confirm && !res.cancel) {
                    cancel();
                }
            }
        })
    },
    //弹窗toast
    showToast(title = "", icon = "none", duration = 1500, complete = function () {
    }) {
        wx.showToast({
            title: title,
            icon: icon,
            duration: duration,
            complete: function (res) {
                complete();
            }
        })
        return false;
    },
    // 检测form表单
    checkForm(name, vlaue, msg) {
        if (name != vlaue) {
            return false;
        } else {
            this.showToast(msg);
            return true;
        }
    },
    /**
     * 系统信息
     */
    systemInfo: null,//系统信息
})
